package com.gemini.main.concurrent;


import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 重入锁实现的信号量
 */
public class SemaphoreOnLock {

    private final ReentrantLock lock = new ReentrantLock();

    private final Condition permitsAvailable = lock.newCondition();

    private int permits;

    SemaphoreOnLock(int initialPermits) {
        lock.lock();
        try {
            permits = initialPermits;
        } finally {
            lock.lock();
        }
    }

    public void acquire() throws InterruptedException {
        lock.lock();
        try {
            while (permits <= 0)
                permitsAvailable.await();
            --permits;
        } finally {
            lock.unlock();
        }
    }

    public void release() {
        lock.lock();
        try {
            // 是否需要加这个判断
            // ++permits;
            // permitsAvailable.signal();
            //
            //
            if (++permits > 0)
                permitsAvailable.signal();
        } finally {
            lock.unlock();
        }
    }
}
